package com.example.blog.controller;

import com.example.blog.Utils.JWTUtils;
import com.example.blog.constant.Contants;
import com.example.blog.model.BlogInfo;
import com.example.blog.result.Result;
import com.example.blog.service.BlogService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.scanner.Constant;

import java.util.List;
@Slf4j
@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping( "/getList")
    public List<BlogInfo> getList(){
      log.info("获取博客列表");
        return blogService.getList();
    }
    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(@NonNull Integer blogId){
        log.info("id是: {}",blogId);
        return blogService.getBlogDetail(blogId);
    }
    @RequestMapping("/add")
    public boolean addBlog(@RequestBody BlogInfo blog, HttpServletRequest request){
        String token = request.getHeader(Contants.TOKEN_HEADER_CONSTANT);
        Integer userId = JWTUtils.getUserIdBytoken(token);
        blog.setUserId(userId);
        Integer result = blogService.insertBlog(blog);
        if(result == null||result == 0){
            return false;
        }
        return true;
    }
    @RequestMapping("/deleteBlog")
    public boolean deleteBlog(@NonNull Integer blogId){
        if(blogId == null||blogId <0){
            return false;
        }
        Integer result = blogService.deleteBlogById(blogId);
        if(result == null||result == 0){
            return false;
        }
        return true;
    }
    @RequestMapping("/updateBlog")
    public Boolean updateBlog(@RequestBody BlogInfo blog){
        if (blog.getId()==null
                || !StringUtils.hasLength(blog.getTitle())
                || !StringUtils.hasLength(blog.getContent())){
            return false;
        }
        blogService.updateBlog(blog);
        return true;
    }
}
